import React, { useEffect, useState } from 'react'
import CarouselCard from './CarouselCard'

const Carousel1 = ({ children }) => {
  const count = React.Children.count(children)
  if (count <= 1 && !children.every((el) => el.type === CarouselCard)) {
    throw new Error('Carousel1 的children必须为CarouselCard元素的数组,而且长度不小于2')
  }
  const { 0: first, [children.length - 1]: last } = children
  // [last,...children,first]
  const newChildren = [React.cloneElement(last, { key: '$first' }), ...children, React.cloneElement(first, { key: '$last' })]

  const [current, setCurrent] = useState(1)
  const [disableTranstion, setDisableTranstion] = useState(false)

  useEffect(() => {
    if (disableTranstion) {
      setDisableTranstion(false)
    }
  }, [disableTranstion])
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrent((current) => current + 1)
    }, 2000)
    return () => {
      clearInterval(timer)
    }
  }, [])
  return (
    <div>
      <div className="carousel1">
        <span className="page">
          {current === count + 1 ? 1 : current}/{count}
        </span>
        <ul
          className={`carousel1-list ${disableTranstion ? '' : 'transition'}`}
          style={{ left: -(current * 100) + '%' }}
          onTransitionEnd={() => {
            if (current === count + 1) {
              // 向右
              setDisableTranstion(true) // 若为true将'transiton' 删除掉
              setCurrent(1) // 重置到开头
            } else if (current === 0) {
              setDisableTranstion(true)
              setCurrent(count)
            }
          }}
        >
          {newChildren}
        </ul>
        <ul className="indicator">
          {[...Array(count)].map((_, index) => (
            <li key={index} className={`${index + 1 === current ? 'current' : ''}`} onClick={() => setCurrent(index + 1)}></li>
          ))}
        </ul>
      </div>
      <button
        onClick={() => {
          let next = current - 1
          setCurrent(next <= 0 ? 0 : next)
        }}
      >
        ←
      </button>
      <button
        onClick={() => {
          let next = current + 1
          setCurrent(next >= count + 1 ? count + 1 : next)
        }}
      >
        →
      </button>
    </div>
  )
}

export default Carousel1
